﻿using System;
using System.Data.Services.Client;
using System.Linq;
using YourWorld.Common.GreenWorldEntitiesService;

namespace MainGameModule.Models
{
    public class QuestionsRepository
    {
        public event Action<DataServiceCollection<Question>> QuestionsLoaded;

        private const string ServiceUrl = @"http://48de1d712dd7438f8e308ea3b1e69aae.cloudapp.net/GreenWorldDataService.svc";
        private GreenWorldEntities context;

        private static QuestionsRepository instance;

        public static QuestionsRepository Instance
        {
            get
            {
                if ( QuestionsRepository.instance == null )
                {
                    QuestionsRepository.instance = new QuestionsRepository();
                }

                return QuestionsRepository.instance;
            }
        }

        public DataServiceCollection<Question> Questions
        {
            get;
            private set;
        }

        public QuestionsRepository()
        {
            this.context = new GreenWorldEntities( new Uri( ServiceUrl, UriKind.RelativeOrAbsolute ) );
        }

        public void Initialize()
        {
            this.LoadQuestionsAsync();
        }

        public void LoadQuestionsAsync()
        {
            var query = from q in this.context.Questions
                        select new Question
                        {
                            Text = q.Text,
                            A = q.A,
                            B = q.B,
                            C = q.C,
                            D = q.D,
                            CorrectAnswer = q.CorrectAnswer,
                            Explanation = q.Explanation,
                        };

            this.Questions = new DataServiceCollection<Question>();
            this.Questions.LoadCompleted += new EventHandler<LoadCompletedEventArgs>( OnQuestionsLoaded );
            this.Questions.LoadAsync( query );
        }

        private void OnQuestionsLoaded( object sender, LoadCompletedEventArgs e )
        {
            if ( this.QuestionsLoaded != null )
            {
                this.QuestionsLoaded( this.Questions );
            }
        }
    }
}
